#include"tree.h"
#include<stdlib.h>
#include<time.h>

int Insert_Tree(BiTree &T,int id,int parent_id)
{
	int i = 0;
	if(T == NULL)
	{
		T = (BiTree)malloc(sizeof(BiTNode));
	        T ->data = rand()%100;
                T ->id = id;
		T ->parent_id = parent_id;
		if(id==6)
		  for(i = 0; i<10 ;i++)
		  {
			  id++;
			  T->childlist[i] = (BiTree)malloc(sizeof(BiTNode));
			  T->childlist[i]->data = rand()%100;
				T->childlist[i]->id = id;
				T->childlist[i]->parent_id = T->id;
			  for(int j=0 ;j<10;j++)
			  {
				  T->childlist[i]->childlist[j] = NULL;
			  } 

		  }
		else
			for(i = 0; i<10 ;i++)
			T->childlist[i] = NULL;
	  return 1;	
  }
	else
	  return 	Insert_Tree(T->childlist[0],id,T->id);
}

void Create_Tree(BiTree &T)
{
        T = NULL;
	//Node_id
	int id = 1;
	//parent_id
	int parent_id = 0;
	srand((unsigned)time(NULL));
	while(id<=7)
	{
		Insert_Tree(T,id,parent_id);
		id++;
		parent_id++;
	}
}

void LevelOrder_Tree(BiTree &T,SqQueue Qu)
{
	if(!T)   return;
	Qu->data[++(Qu->rear)] = T;
	BiTree p = (BiTree)malloc(sizeof(BiTNode));
	while(Qu->front < Qu->rear)
	{
		p = Qu->data[++Qu->front];
	  for(int i=0; i<10; i++)
	  {
		   if(p->childlist[i] != NULL)
		   {
			   Qu->data[++(Qu->rear)] = p->childlist[i];
		   }
	  }
	}
}


int main()
{
	BiTree  T = NULL;
	SqQueue Qu;
	Qu = (SqQueue)malloc(sizeof(SqQu));
	Qu->front = Qu->rear = -1;

	Create_Tree(T);
	LevelOrder_Tree(T,Qu);

	int Node_counts = 0, i =0;
	Node_counts = Qu->rear-1;
        FILE *fd_in,*fd_out;

	fd_in = fopen("1.txt", "w");
	fwrite(&Node_counts,sizeof(int),1,fd_in);
	while(i <= Node_counts)
	{
	printf("The Node data is %2d,Node id is %2d ,parent_id is %2d\n",Qu->data[i]->data,Qu->data[i]->id,Qu->data[i]->parent_id);
	fwrite(Qu->data[i],sizeof(BiTNode),1,fd_in);
	i++;
	}
	fclose(fd_in);
	return 0;
}
